package com.situ.stmall.manger.controller.api;

import com.github.pagehelper.PageInfo;
import com.situ.stmall.manger.entity.Goods;
import com.situ.stmall.manger.entity.Result;
import com.situ.stmall.manger.service.GoodsService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/api/goods")
public class APIGoodsController {
    @Resource
    private GoodsService goodsService;
    //添加商品
    @PostMapping
    public Result add(@RequestBody Goods goods){
        try {
            int code =goodsService.add(goods);
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.getMessage());
        }
    }

    //删除商品
    @DeleteMapping
    public Result remove(Integer id){
        try {
            goodsService.remove(id);
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.getMessage());
        }
    }
    //修改商品
    @PutMapping
    public Result edit(@RequestBody Goods goods){
        try {
            goodsService.edit(goods);
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.getMessage());
        }
    }

    //根据id查询商品
    @GetMapping("/{id}")
    public Result get(@PathVariable("id") Integer id){
        try {
            Goods goods = goodsService.getById(id);
            return Result.success(goods);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.getMessage());
        }
    }

    @GetMapping
    public Result search(Integer page,Integer limit,Goods goods){
        if (page==null){
            List<Goods> list = goodsService.search(goods);
            return Result.success(list);
        }else {
            PageInfo pageInfo = goodsService.searchByPage(page, limit, goods);
            return Result.success(pageInfo);
        }
    }
}
